package com.ktg.mes.qc.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.qc.domain.*;
import com.ktg.mes.qc.service.*;
import com.ktg.mes.wm.domain.WmItemRecptLine;
import com.ktg.mes.wm.service.IWmItemRecptLineService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.poi.ExcelUtil;

import static com.ktg.mes.util.LService.recordId;

/**
 * 检测模板-产品检测汇总Controller
 *
 * @author byteco
 * @date 2022-12-06
 */
@RestController
@RequestMapping("/qc/qcItemTemplate")
public class QcItemTemplateController extends BaseController
{
    @Autowired
    private IQcItemTemplateService qcItemTemplateService;

    @Autowired
    private IQcItemTemplateIndexService iQcItemTemplateIndexService;

    @Autowired
    private IQcTemplateService templateService;

    @Autowired
    private IQcTemplateProductService templateProductService;

    @Autowired
    private IWmItemRecptLineService wmItemRecptLineService;

    @Autowired
    private IQcTemplateIndexService qcTemplateIndexService;

    @Autowired
    private IQcItemTemplateIndexService qcItemTemplateIndexService;


    @Autowired
    private IQcTemplateService iQcTemplateService;

    /**
     * 查询检测模板-产品检测汇总列表
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:list')")
    @GetMapping("/list")
    public Result<IPage<QcItemTemplate>> list(QcItemTemplate qcItemTemplate,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询检测模板-产品检测汇总列表",req,null);
        try {
            Page<QcItemTemplate> page = new Page<QcItemTemplate>(pageNo, pageSize);
            IPage<QcItemTemplate> pageList = qcItemTemplateService.queryPageList(qcItemTemplate,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出检测模板-产品检测汇总列表
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:export')")
    @Log(title = "检测模板-产品检测汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QcItemTemplate qcItemTemplate,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出检测模板-产品检测汇总列表",req,qcItemTemplate);
        try {
            List<QcItemTemplate> list = qcItemTemplateService.queryList(qcItemTemplate);
            ExcelUtil<QcItemTemplate> util = new ExcelUtil<QcItemTemplate>(QcItemTemplate.class);
            util.exportExcel(response, list, "检测模板-产品检测汇总数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取检测模板-产品检测汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:query')")
    @GetMapping(value = "/{recordId}")
    public Result<QcItemTemplate> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取检测模板-产品检测汇总详细信息",req,null);
        try {
            return apiLog.ok(qcItemTemplateService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 获取检测模板-产品检测汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:query')")
    @GetMapping(value = "/getTemplateInfo/{lineId}")
    public Result<QcItemTemplate> getTemplateInfo(@PathVariable("lineId") Long lineId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取检测模板-产品检测汇总详细信息",req,null);
        try {

            WmItemRecptLine wmItemRecptLine = wmItemRecptLineService.selectWmItemRecptLineByLineId(lineId);

            //产品检测信息
            QcTemplateProduct templateProduct = new QcTemplateProduct();
            templateProduct.setItemId(wmItemRecptLine.getItemId());
            QueryWrapper<QcTemplateProduct> qcTemplateProductQueryWrapper = new QueryWrapper<>(templateProduct);
            templateProduct = templateProductService.getOne(qcTemplateProductQueryWrapper);
            if (templateProduct == null){
                return apiLog.fail("当前生产的产品未配置此类型的检验模板！");
            }

            //产品检测信息
            QcTemplate template = templateService.getById(templateProduct.getTemplateId());
            if (template == null){
                return apiLog.fail("当前生产的产品未配置此类型的检验模板！");
            }


//            //查询旧的检测单
//            QcItemTemplate itemTemplate = new QcItemTemplate();
//            itemTemplate.setItemId(String.valueOf(itemId));
//            QueryWrapper<QcItemTemplate> itemTemplateQueryWrapper = new QueryWrapper<>(itemTemplate);
//            itemTemplateQueryWrapper.ne("template_id",templateProduct.getTemplateId());
//            List<QcItemTemplate> itemTemplateList = qcItemTemplateService.list(itemTemplateQueryWrapper);
//            if (itemTemplateList != null && itemTemplateList.size() > 0){
//                for (int i = 0;i < itemTemplateList.size();i++){
//                    qcItemTemplateService.delete(itemTemplate.getTemplateId());
//
//                    QueryWrapper<QcItemTemplateIndex> itemTemplateIndexQueryWrapper = new QueryWrapper<>();
//                    itemTemplateIndexQueryWrapper.eq("item_template_id",itemTemplate.getItemTemplateId());
//                    iQcItemTemplateIndexService.remove(itemTemplateIndexQueryWrapper);
//                }
//            }

            //具体产品检测信息
            QcItemTemplate itemTemplate = new QcItemTemplate();
            itemTemplate.setLinkType("wm_item_recpt_line");
            itemTemplate.setLinkId(String.valueOf(wmItemRecptLine.getLineId()));
            QueryWrapper<QcItemTemplate>itemTemplateQueryWrapper = new QueryWrapper<>(itemTemplate);
            itemTemplate = qcItemTemplateService.getOne(itemTemplateQueryWrapper);

            if (itemTemplate == null){
                itemTemplate = new QcItemTemplate();
                itemTemplate.setTemplateId(template.getTemplateId());
                itemTemplate.setLinkType("wm_item_recpt_line");
                itemTemplate.setLinkId(String.valueOf(wmItemRecptLine.getLineId()));
                itemTemplate.setItemId(String.valueOf(templateProduct.getItemId()));
                itemTemplate.setItemCode(itemTemplate.getItemCode());
                itemTemplate.setItemName(itemTemplate.getItemName());
                itemTemplate.setSpecification(itemTemplate.getSpecification());
                itemTemplate.setUnitOfMeasure(itemTemplate.getUnitOfMeasure());
                itemTemplate.setQuantityCheck(itemTemplate.getQuantityCheck());
                itemTemplate.setQuantityUnqualified(itemTemplate.getQuantityUnqualified());
                itemTemplate.setCrRate(itemTemplate.getCrRate());
                itemTemplate.setMajRate(itemTemplate.getMajRate());
                itemTemplate.setStatus(wmItemRecptLine.getStatus());

                qcItemTemplateService.save(itemTemplate);


                //产品检测信息
                QcTemplateIndex templateIndex = new QcTemplateIndex();
                templateIndex.setTemplateId(template.getTemplateId());
                QueryWrapper<QcTemplateIndex> templateIndexQueryWrapper = new QueryWrapper<>(templateIndex);
                List<QcTemplateIndex> templateIndexList = qcTemplateIndexService.list(templateIndexQueryWrapper);

                for (int i = 0;i < templateIndexList.size();i++){
                    // QcTemplateIndex qcTemplateIndex = new QcTemplateIndex();
                    QcTemplateIndex qcTemplateIndex = templateIndexList.get(i);
                    QcItemTemplateIndex index = new QcItemTemplateIndex();

                    index.setItemTemplateId(itemTemplate.getItemTemplateId());
                    index.setTemplateId(itemTemplate.getTemplateId());

                    index.setIndexId(qcTemplateIndex.getIndexId());
                    index.setIndexCode(qcTemplateIndex.getIndexCode());
                    index.setIndexName(qcTemplateIndex.getIndexName());
                    index.setIndexType(qcTemplateIndex.getIndexType());
                    index.setCheckMethod(qcTemplateIndex.getCheckMethod());
                    index.setStanderVal(qcTemplateIndex.getStanderVal());
                    index.setUnitOfMeasure(qcTemplateIndex.getUnitOfMeasure());
                    index.setThresholdMax(qcTemplateIndex.getThresholdMax());
                    index.setThresholdMin(qcTemplateIndex.getThresholdMin());

                    index.setItemId(String.valueOf(templateProduct.getItemId()));
                    index.setItemCode(templateProduct.getItemCode());
                    index.setItemName(templateProduct.getItemName());
                    index.setSpecification(templateProduct.getSpecification());
                    index.setItemUnitOfMeasure(qcTemplateIndex.getUnitOfMeasure());

                    qcItemTemplateIndexService.save(index);
                }

            }
            itemTemplate.setStatus(wmItemRecptLine.getStatus());

            return apiLog.ok(itemTemplate);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增检测模板-产品检测汇总
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:add')")
    @Log(title = "检测模板-产品检测汇总", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody QcItemTemplate qcItemTemplate,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增检测模板-产品检测汇总",req,qcItemTemplate);
        try {
            qcItemTemplateService.insert(qcItemTemplate);

            WmItemRecptLine wmItemRecptLine = wmItemRecptLineService.selectWmItemRecptLineByLineId(Long.valueOf(qcItemTemplate.getLinkId()));

            wmItemRecptLine.setStatus(qcItemTemplate.getStatus());
            wmItemRecptLineService.updateById(wmItemRecptLine);

            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改检测模板-产品检测汇总
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:edit')")
    @Log(title = "检测模板-产品检测汇总", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody QcItemTemplate qcItemTemplate,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改检测模板-产品检测汇总",req,qcItemTemplate);
        try {
            qcItemTemplateService.update(qcItemTemplate);

            WmItemRecptLine wmItemRecptLine = wmItemRecptLineService.selectWmItemRecptLineByLineId(Long.valueOf(qcItemTemplate.getLinkId()));

            wmItemRecptLine.setStatus(qcItemTemplate.getStatus());
            wmItemRecptLineService.updateById(wmItemRecptLine);

            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除检测模板-产品检测汇总
     */
    @PreAuthorize("@ss.hasPermi('qc:qcItemTemplate:remove')")
    @Log(title = "检测模板-产品检测汇总", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除检测模板-产品检测汇总",req,null);
        try {
            qcItemTemplateService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }

    @GetMapping("/findIqcTemplate")
    public AjaxResult findIqc(Long itemId, String type){
        QcTemplate param = new QcTemplate();
        param.setItemId(itemId);
        param.setQcTypes(type);
        List<QcTemplate> qcTemplates = iQcTemplateService.selectQcTemplateListByPro(param);
        if(CollUtil.isNotEmpty(qcTemplates)){
            return AjaxResult.success(qcTemplates);
        }else{
            return AjaxResult.error("当前产品未配置检测模板！");
        }
    }
}
